package cn.skycity.common.controller;

import cn.hutool.core.util.StrUtil;
import cn.skycity.common.service.ISysDictTypeService;
import cn.skycity.framework.core.model.Result;
import cn.skycity.framework.core.utils.LangUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.skycity.common.log.annotation.Log;
import com.skycity.common.log.enums.BusinessType;
import com.skycity.framework.uaa.pojo.entity.SysDictType;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Stream;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author YingBo.Dai
 * @since 2024-12-13
 */
@RestController
@RequestMapping("/dict")
public class SysDictTypeController {
    @Resource
    private ISysDictTypeService sysDictTypeService;

    @GetMapping("/page")
    public Result<Page<SysDictType>> pageList(Page<SysDictType> pageVo, SysDictType sysDictType) {
        LambdaQueryWrapper<SysDictType> queryWrapper = new LambdaQueryWrapper<SysDictType>()
                .like(StrUtil.isNotBlank(sysDictType.getDictType()), SysDictType::getDictType, sysDictType.getDictType())
                .orderByDesc(SysDictType::getId);
        Page<SysDictType> result = sysDictTypeService.page(pageVo, queryWrapper);
        return Result.success(result);
    }

    @GetMapping("/{id}")
    public Result<SysDictType> getDictType(@PathVariable("id") Long id) {
        return Result.success(sysDictTypeService.getById(id));
    }

    @Log(title = "字典类型", businessType = BusinessType.INSERT)
    @PostMapping
    public Result<?> add(@RequestBody SysDictType sysDict) {
        long count = sysDictTypeService.count(new LambdaQueryWrapper<SysDictType>().eq(SysDictType::getDictType, sysDict.getDictType()));
        if (count > 0) {
            return Result.failed(LangUtil.getMessage("dict.code.exist"));
        }
        sysDictTypeService.save(sysDict);
        return Result.success();
    }

    @PutMapping
    @Log(title = "字典类型", businessType = BusinessType.UPDATE)
    public Result<?> update(@RequestBody SysDictType sysDict) {
        long count = sysDictTypeService.count(new LambdaQueryWrapper<SysDictType>().eq(SysDictType::getDictType, sysDict.getDictType()).ne(SysDictType::getId, sysDict.getId()));
        if (count > 0) {
            return Result.failed(LangUtil.getMessage("dict.code.exist"));
        }
        sysDictTypeService.updateById(sysDict);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    @Log(title = "字典类型", businessType = BusinessType.DELETE)
    public Result<?> delete(@PathVariable("id") String ids) {
        List<Long> idArr = Stream.of(ids.split(",")).map(Long::parseLong).toList();
        idArr.forEach(id->{
            sysDictTypeService.deleteByCode(id);
        });
        return Result.success();
    }
}
